<template>
  <div>
    <div>
      <div style="text-align: right; margin-bottom: 8px">
        <a-tooltip>
          <template #title
            ><span v-if="editModel">切换到视图模式</span
            ><span v-if="!editModel">切换到编辑模式</span></template
          >
          <a-button size="small" style="width: 34px" @click="toggleModel">
            <EditOutlined v-if="!editModel" />
            <BookOutlined v-else />
          </a-button>
        </a-tooltip>
      </div>
      <Editor
        v-if="editModel"
        v-model:value="props.value"
        @change="handleChange"
        mode="split"
        :plugins="plugins"
        :uploadImages="uploadImages"
        :editorConfig="editorConfig"
      />
    </div>
    <Viewer v-if="!editModel" :value="props.value" :plugins="plugins" />
  </div>
</template>

<script setup>
import { ref, onMounted, markRaw, watch } from "vue";

import {
  FileMarkdownOutlined,
  EditOutlined,
  BookOutlined,
} from "@ant-design/icons-vue";

import { Editor, Viewer } from "@bytemd/vue-next";
import gfm from "@bytemd/plugin-gfm";
import highlight from "@bytemd/plugin-highlight";
import gemoji from "@bytemd/plugin-gemoji";
import math from "@bytemd/plugin-math-ssr";
import mermaid from "@bytemd/plugin-mermaid";
import "highlight.js/styles/default.css"; // 代码高亮样式
import "@/assets/juejin.css";
import { messageApi, contextHolder } from "@/utils/MessageUtils.js";
// import "juejin-markdown-themes/dist/juejin.min.css"; // 掘金样式

import "bytemd/dist/index.css";

const props = defineProps({
  value: {
    type: String,
    default: "",
  },
  canEdit: {
    type: Boolean,
    default: true,
  },
  folderName: {
    type: String,
    default: "",
  },
});

const editModel = ref(props.canEdit);

const emits = defineEmits(["update:value"]);

const plugins = [
  gfm(),
  highlight(), // 代码高亮插件
  math(), // 数学公式插件
  gemoji(), //  Support Gemoji shortcodes
  mermaid(), // 流程图插件
];
function handleChange(x) {
  emits("update:value", x);
}

const editorConfig = {
  placeholder: "请输入内容...",
};

// 上传图片
async function uploadImages(files) {
  const resultData = [];
  const cfg = import.meta.env;
  console.log("====== cfg : ====", cfg);
  const baseURL = cfg.VITE_UPLOAD_BASE_URL;
  for (const item of files) {
    const formData = new FormData();
    formData.append("file", item);
    formData.append("folderName", props.folderName);
    const res = await fetch(`${baseURL}/kc/upload`, {
      method: "POST",
      body: formData,
    });
    const data = await res.json();
    // alert(JSON.stringify(data));
    if (data?.code == "200") {
      // 上传成功后安装指定格式返回
      resultData.push({
        url: data.msg,
        alt: item.name,
        title: item.name,
      });
    } else {
      alert("上传失败");
    }
  }
  return resultData;
}

function toggleModel() {
  editModel.value = !editModel.value;
}
</script>

<style>
.bytemd-fullscreen.bytemd {
  z-index: 999999 !important;
}
</style>